package com.applet.system.config;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.applet.system.entity.UserContext;
import com.applet.system.utils.UserContextUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import com.alibaba.fastjson.JSON;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 配置session用户上下文
 * @author 1217460714@qq.com
 * data:2019-11-22
 */
@Configuration
public class ConsoleWebMvcConfigurer extends WebMvcConfigurerAdapter{
	private static final String ingoreUrls[]={"verificationCode","login"};
	@Bean
	public HandlerInterceptor getInterceptor(){
		return new HandlerInterceptor() {

			@Override
			public boolean preHandle(HttpServletRequest req, HttpServletResponse response,
									 Object arg2) throws Exception {
				//HttpSession se=req.getSession();
				String uri=req.getRequestURI();

				Object obj = req.getSession().getAttribute(UserContext.class.getName());

				if (obj != null) {
					UserContext user = JSON.parseObject(obj.toString(), UserContext.class);
					UserContextUtil.set(user);
				}else{
					boolean isIgnore=false;
					for(String ingoreUrl:ingoreUrls){
						if(uri.contains(ingoreUrl)){
							isIgnore=true;
						}
					}
					if(!isIgnore){
						response.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));//设置允许哪些域名应用进行ajax访问
						response.setHeader("Access-Control-Allow-Methods", "*");
						response.setHeader("Access-Control-Allow-Headers", "*");
						response.setHeader("Access-Control-Allow-Credentials", "true");
						PrintWriter printWriter=response.getWriter();
						Map map=new HashMap();
						map.put("code",401);
						map.put("msg","登录超时");
						printWriter.write(JSON.toJSONString(map));
						printWriter.close();
						return  false;
					}
				}
				return true;
			}

			@Override
			public void postHandle(HttpServletRequest req, HttpServletResponse arg1,
								   Object arg2, ModelAndView arg3) throws Exception {
			}

			@Override
			public void afterCompletion(HttpServletRequest arg0,
										HttpServletResponse arg1, Object arg2, Exception arg3)
					throws Exception {

			}
		};
	}

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(getInterceptor()).addPathPatterns("/**");
		super.addInterceptors(registry);
	}
}
